<template>
  <div class="w-full">
    <van-form @failed="onFailed" ref="formRef">
      <van-cell-group inset>
        <van-field
          v-model="Info.mobile"
          name="pattern"
          placeholder="请输入手机号"
          label="手机号"
          :rules="[{ pattern, message: '请输入正确手机号' }]"
        />

        <van-field
          v-model="Info.code"
          placeholder="请输入验证码"
          label="验证码"
          name="验证码"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              :disabled="disabled"
              @click="handleCode"
              >{{ codeText }}</van-button
            >
          </template></van-field
        >
        <van-field
          v-model="Info.password"
          placeholder="请输入密码"
          type="password"
          label="新密码"
          name="新密码"
        />
      </van-cell-group>
      <div style="margin: 16px" @click="sumbit">
        <van-button block type="primary" native-type="submit">
          确认修改
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script setup>
import { getMobileCode, editPassword } from "@/util/api";
import { showToast } from "vant";
import { useRouter } from "vue-router";
const Info = reactive({
  mobile: "",
  code: "",
  password: "",
});
const router = useRouter();
const formRef = ref(null);
const disabled = ref(false);
const codeText = ref("发送验证码");
const time = ref(60);
const pattern =
  /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
const onFailed = (v) => {
  console.log(v);
};
const handleCode = async () => {
  formRef.value
    .validate()
    .then(async () => {
      const res = await getMobileCode({ mobile: Info.mobile, type: 4 });
      showToast(res.msg);
      disabled.value = true;
      let timer = setInterval(() => {
        time.value--;
        if (time.value) {
          codeText.value = time.value + "秒后重新发送";
        } else {
          timer = clearInterval(timer);
          disabled.value = false;
          time.value = 60;
          codeText.value = "获取验证码";
        }
      }, 1000);
    })
    .catch((err) => {});

  //   发送验证码
};
const sumbit = () => {
  formRef.value
    .validate()
    .then(async () => {
      const res = await editPassword(Info);
      showToast(res.msg);
      res.code == 1 ? router.go(-1) : "";
    })
    .catch((err) => {
      // console.log(err);
    });
};
</script>
